<?php

class courseActions extends samsungActions {

  public function executeIndex(sfWebRequest $request) {
    $this->categories = CATEGORYTable::getInstance()->getCategories(true, false);
    $courses = COURSETable::getInstance()->getCourses();
    $categoryCourseMap = array();
    foreach ($courses as $course) {
      $categoryCourseMap[$course->getCategoryId()][] = $course;
    }
    $this->courses = $categoryCourseMap;
  }

  public function executeSlide(sfWebRequest $request) {
    $courseId = $request->getParameter('course_id');
    $slideNum = $request->getParameter('slide_num');
    
    if ($slideNum == 1 && $request->getParameter('start') == 'y') {
      $this->_clearSessionData($courseId);
    }

    $course = COURSETable::getInstance()->getCourse($courseId);
    $this->forward404Unless($course);

    $slideCount = $this->getUser()->getAttribute(Constants::SESSION_SLIDE_COUNT . '_' . $courseId);
    if (!$slideCount) {
      $slideCount = SLIDETable::getInstance()->getCountByCourseId($courseId);
      $this->getUser()->setAttribute(Constants::SESSION_SLIDE_COUNT . '_' . $courseId, $slideCount);
    }

    $this->forward404Unless($slideCount);

    $slidesViewed = $this->getUser()->getAttribute(Constants::SESSION_SLIDES_VIEWED . '_' . $courseId, array());
    if (!in_array(($slideNum - 1), $slidesViewed) && $slideNum != 1) {
      $gotoSlide = count($slidesViewed) ? (max($slidesViewed)) : 1;
      $this->redirect('@slide?course_id=' . $course->getId() . '&slide_num=' . $gotoSlide);
    }
    $slidesViewed[] = $slideNum;
    $slidesViewed = array_unique($slidesViewed);
    $this->getUser()->setAttribute(Constants::SESSION_SLIDES_VIEWED . '_' . $courseId, $slidesViewed);
    
    if (!$this->getUser()->hasAttribute(Constants::SESSION_IS_USER_PASSED . '_' . $courseId)) {
      $this->getUser()->setAttribute(Constants::SESSION_IS_USER_PASSED . '_' . $courseId, USER_SCORETable::getInstance()->isUserPassed($courseId, $this->getUser()->getAttribute(Constants::SESSION_USER_ID)));
    }

    $slide = SLIDETable::getInstance()->getByCourseId($course->getId(), $slideNum);
    $this->forward404Unless(count($slide));
    $this->slide = $slide[0];
    $this->course = $course;
    $this->slideCount = $slideCount;
    $this->isFirstSlide = ($slideNum == 1);
    $this->isLastSlide = ($slideNum == $slideCount);
    $this->isUserPassed = $this->getUser()->getAttribute(Constants::SESSION_IS_USER_PASSED . '_' . $courseId);
  }

  public function executeQuestion(sfWebRequest $request) {
    $courseId = $request->getParameter('course_id');
    $questionNum = $request->getParameter('question_num');

    $course = COURSETable::getInstance()->getCourse($courseId);
    $this->forward404Unless($course);

    $questionCount = $this->getUser()->getAttribute(Constants::SESSION_QUESTION_COUNT . '_' . $courseId);
    if (!$questionCount) {
      $questionCount = QUESTIONTable::getInstance()->getCountByCourseId($courseId);
      $this->getUser()->setAttribute(Constants::SESSION_QUESTION_COUNT . '_' . $courseId, $questionCount);
    }

    $this->forward404Unless($questionCount);

    $questionsAnswered = array_keys($this->getUser()->getAttribute(Constants::SESSION_QUESTIONS_RESULT . '_' . $courseId, array()));
    if (!in_array(($questionNum - 1), $questionsAnswered) && $questionNum != 1) {
      $gotoQuestion = count($questionsAnswered) ? (max($questionsAnswered)) : 1;
      $this->redirect('@question?course_id=' . $course->getId() . '&question_num=' . $gotoQuestion);
    }

    $question = QUESTIONTable::getInstance()->getByCourseId($course->getId(), $questionNum);
    $this->forward404Unless(count($question));
    $this->question = $question[0];

    $choices = CHOICETable::getInstance()->getByQuestionId($question[0]->getId());
    $this->forward404Unless(count($choices));
    $this->choices = $choices;
    
    $this->forward404If($this->getUser()->getAttribute(Constants::SESSION_IS_USER_PASSED . '_' . $courseId));

    $this->course = $course;
    $this->questionCount = $questionCount;
    $this->isFirstQuestion = ($questionNum == 1);
    $this->isLastQuestion = ($questionNum == $questionCount);

    $slidesViewed = $this->getUser()->getAttribute(Constants::SESSION_SLIDES_VIEWED . '_' . $courseId, array());
    $slideCount = $this->getUser()->getAttribute(Constants::SESSION_SLIDE_COUNT . '_' . $courseId);
    if (!count($slidesViewed) || $slideCount != count($slidesViewed)) {
      $this->redirect('@slide?course_id=' . $course->getId() . '&slide_num=1');
    }
    $this->lastSlideNum = max($slidesViewed);
    
    $questionsChoice = $this->getUser()->getAttribute(Constants::SESSION_QUESTIONS_CHOICE . '_' . $courseId, array());
    $this->selChoice = (isset($questionsChoice[$questionNum])) ? $questionsChoice[$questionNum] : NULL;

    if ($request->isMethod('post')) {
      $choice = $request->getParameter('choice');
      $questionsResult = $this->getUser()->getAttribute(Constants::SESSION_QUESTIONS_RESULT . '_' . $courseId, array());
      $questionsResult[$questionNum] = $choices[$choice]->getIsCorrect();
      $this->getUser()->setAttribute(Constants::SESSION_QUESTIONS_RESULT . '_' . $courseId, $questionsResult);
      
      $questionsChoice = $this->getUser()->getAttribute(Constants::SESSION_QUESTIONS_CHOICE . '_' . $courseId, array());
      $questionsChoice[$questionNum] = $choice;
      $this->getUser()->setAttribute(Constants::SESSION_QUESTIONS_CHOICE . '_' . $courseId, $questionsChoice);

      /*
      try {
        $userResponse = new USER_RESPONSE();
        $userResponse->setUserId($this->getUser()->getAttribute(Constants::SESSION_USER_ID));
        $userResponse->setQuestionId($question[0]->getId());
        $userResponse->setChoiceId($choices[$choice]->getId());
        $userResponse->save();
      } catch (Exception $e) {
        
      }
      */

      if (!$this->isLastQuestion) {
        $this->redirect('@question?course_id=' . $course->getId() . '&question_num=' . ($questionNum + 1));
      } else {
        $this->redirect('@result?course_id=' . $course->getId());
      }
    }
  }

  public function executeResult(sfWebRequest $request) {
    $courseId = $request->getParameter('course_id');

    $course = COURSETable::getInstance()->getCourse($courseId);
    $this->forward404Unless($course);

    if (!$this->getUser()->getAttribute(Constants::SESSION_QUESTION_COUNT . '_' . $courseId)) {
      $this->redirect('@slide?course_id=' . $course->getId() . '&slide_num=1');
    }

    $questionsResult = $this->getUser()->getAttribute(Constants::SESSION_QUESTIONS_RESULT . '_' . $courseId, array());
    if (!count($questionsResult) || (count($questionsResult) != $this->getUser()->getAttribute(Constants::SESSION_QUESTION_COUNT . '_' . $courseId))) {
      $this->redirect('@question?course_id=' . $course->getId() . '&question_num=1');
    }

    $correctCount = 0;
    foreach ($questionsResult as $res) {
      if ($res == 1) {
        $correctCount++;
      }
    }
    
    $this->course = $course;
    $this->score = round(($correctCount/count($questionsResult))*100, 2);

    try {
      $userScore = new USER_SCORE();
      $userScore->setUserId($this->getUser()->getAttribute(Constants::SESSION_USER_ID));
      $userScore->setCourseId($courseId);
      $userScore->setScore($this->score);
      $userScore->save();
    } catch (Exception $e) {
      
    }
    
    if ($this->score == 100) {
        $phpMailer = new PHPMailer();
        //$phpMailer->Host = sfConfig::get('app_email_host');
        //$phpMailer->IsSMTP();
        //$phpMailer->SMTPAuth = true;
        //$phpMailer->Port = sfConfig::get('app_email_port');
        $phpMailer->Timeout = 60;
        $phpMailer->CharSet = 'UTF-8';
        //$phpMailer->Username = sfConfig::get('app_email_username');
        //$phpMailer->Password = sfConfig::get('app_email_password');
        $phpMailer->AddAddress($this->getUser()->getAttribute(Constants::SESSION_EMAIL));
        $phpMailer->From = 'info@samsung.com';
        $phpMailer->FromName = 'Samsung';
        $phpMailer->AddReplyTo('no-reply@samsung.com');
        $phpMailer->Subject = 'Samsung - Course completed';

        $message = 'Congratulations! You passed the course "' . $course->getTitle() . "\"!\n\n";

        $phpMailer->Body = $message;
        $phpMailer->IsHTML(false);
        $phpMailer->Send();
    }
    
    $this->_clearSessionData($courseId);
  }
  
  private function _clearSessionData($courseId) {
    $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_SLIDE_COUNT . '_' . $courseId);
    $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_SLIDES_VIEWED . '_' . $courseId);
    $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_QUESTION_COUNT . '_' . $courseId);
    $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_QUESTIONS_RESULT . '_' . $courseId);
    $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_QUESTIONS_CHOICE . '_' . $courseId);
    $this->getUser()->getAttributeHolder()->remove(Constants::SESSION_IS_USER_PASSED . '_' . $courseId);
  }
}